<?php
/**
 * @Name: UsersServices.php
 * @Author: yashuai<1762910894@qq.com>
 */

namespace app\common\services\rbac;

use app\common\logic\rbac\UsersLogic;
use app\common\services\BaseServices;
use HugCode\PhpUnits\CipherText\Password;
use HugCode\PhpUnits\Frame\Code\ConstCode;

class UsersServices extends BaseServices
{

    public function __construct(UsersLogic $logic)
    {
        $this->logic = $logic;
    }

    /**
     * @Desc 列表
     * @param array $params
     * @return array
     * @author yashuai<1762910894@qq.com>
     */
    public function getList(array $params = [])
    {
        $where  = [
            'UserStatus' => _array_field($params, 'Status', ConstCode::BASIC_STATUS_NORMAL)
        ];
        $select = ['UserID', 'UserName', 'NickName', 'UserEmail', 'IsSuper', 'UserStatus', 'CreateTime'];

        $result = $this->getPageList($where, $select, ['role', 'role.role']);
        foreach ($result['list'] as &$val) {
            $val['RoleID']   = [];
            $val['RoleList'] = [];
            if ($val['IsSuper'] == ConstCode::IS_NO) {
                $val['RoleID']   = array_column($val['role'], 'RoleID');
                $val['RoleList'] = array_column($val['role'], 'role');
            }
            unset($val['role']);
        }
        return $result;
    }

    /**
     * @Desc 添加
     * @param array $params
     * @return mixed
     * @author yashuai<1762910894@qq.com>
     */
    public function createData(array $params = [])
    {
        $this->validatorUserName($params['UserName']);
        $params['UserID'] = $this->createRow($params);
        if (_array_field($params, 'RoleID')) {
            /** @var UsersRoleServices $userRoleService */
            $userRoleService = app()->make(UsersRoleServices::class);
            $userRoleService->setUserRole($params);
        }
        return $params['UserID'];
    }

    /**
     * @Desc 编辑
     * @param array $params
     * @return mixed
     * @author yashuai<1762910894@qq.com>
     */
    public function updateData(array $params = [])
    {
        $this->validatorUserName($params['UserName'], $params['UserID']);
        $result = $this->updateRow($params);
        if (_array_field($params, 'RoleID')) {
            /** @var UsersRoleServices $userRoleService */
            $userRoleService = app()->make(UsersRoleServices::class);
            $userRoleService->setUserRole($params);
        }
        return $result;
    }

    /**
     * @Desc 删除用户
     * @param array $params
     * @return mixed
     * @author yashuai<1762910894@qq.com>
     */
    public function deleteData(array $params)
    {
        if ($params['Status'] == ConstCode::BASIC_STATUS_DELETE) {
            $info = $this->validatorRow($params['ID'], ['UserID', 'IsSuper']);
            if ($info['IsSuper'] == 1) {
                _throw('超级管理员不能删除', 106001);
            }
        }
        return $this->updateStatus(['UserID' => $params['ID']], $params['Status']);
    }

    /**
     * @Desc 获取用户信息
     * @param int $userId
     * @return array
     * @author yashuai<1762910894@qq.com>
     */
    public function info(int $userId)
    {
        $select = [
            'UserID', 'UserName', 'NickName', 'UserStatus', 'IsSuper'
        ];
        $this->get($userId, $select);

        /** @var UsersRoleServices $userRoleService */
        $userRoleService = app()->make(UsersRoleServices::class);
        /** @var NodeServices $nodeService */
        $nodeService = app()->make(NodeServices::class);

        $info['roles'] = $userRoleService->column(['UserID' => $userId], 'RoleID');

        $node = $nodeService->getUserNode($userId, true);
        foreach ($node as $val) {
            $info['authorities'][] = [
                'authority' => $val['ControllerName'] . ':' . $val['ActionName'],
                'title'     => $val['title']
            ];
        }

        $info['fileHost'] = env('STATIC_HOST', '');
        $info['webHost']  = env('WEB_HOST', '');
        return $info;
    }

    /**
     * @Desc 验证有用户名
     * @param string $name
     * @param int $userId
     * @author yashuai<1762910894@qq.com>
     */
    public function validatorUserName(string $name, int $userId = 0)
    {
        $where = [
            ['UserName', '=', $name],
        ];
        if (!empty($userId)) {
            $where[] = ['UserID', '<>', $userId];
        }
        if (!empty($this->get($where))) {
            _throw('当前用户名已存在', 106003);
        }
    }

    /**
     * @Desc 修改密码
     * @param array $params
     * @param bool $is_my 修改自己的密码
     * @return mixed
     * @author yashuai<1762910894@qq.com>
     */
    public function resetPassword(array $params, bool $is_my = false)
    {
        $info = $this->validatorRow($params['UserID'], ['UserPassword']);
        if (
            $is_my &&
            !empty($info['UserPassword']) &&
            !Password::validatePassword($params['OriginalPassword'], $info['UserPassword'])
        ) {
            _throw('原始密码错误', 107002);
        }
        return $this->update($params['UserID'], [
            'UserPassword' => Password::generatePassword($params['UserPassword'])
        ]);
    }

}
